package com.ld.admin.service.system.dbbackup;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.ld.admin.model.system.dbbackup.DbBackupManageModel;
import com.ld.admin.model.system.dbbackup.DbBackupSetModel;
import com.ld.admin.model.system.dbbackup.DbbackUpInfoModel;
import com.ld.admin.service.system.dbbackup.queue.DBRecoveryThread;
import com.ld.admin.service.system.dbbackup.queue.DBbackupThread;
import com.ld.common.service.ProjectBasicService;
import com.ld.shieldsb.common.core.io.FileUtils;
import com.ld.shieldsb.common.core.model.PropertiesModel;
import com.ld.shieldsb.common.core.model.Result;
import com.ld.shieldsb.common.core.util.DateUtil;
import com.ld.shieldsb.common.web.BasicService;
import com.ld.shieldsb.common.web.util.Web;
import com.ld.shieldsb.dao.model.QueryModel;
import com.ld.shieldsb.db.model.DBSetInfo;

@Service
public class DbBackUpService extends ProjectBasicService {
    public static final BasicService basicService = new BasicService();

    public void mysqlBack(DBSetInfo dbSetInfo, DbBackupSetModel backupSetModel) {
        QueryModel queryModel = basicService.getNormalQueryModel();
        DbBackupManageModel backupManageModel = basicService.getOne(DbBackupManageModel.class, queryModel);
        String uploadRootPath = "";
        if (backupManageModel != null && StringUtils.isNotEmpty(backupManageModel.getBackupFileLocation())) {
            uploadRootPath = backupManageModel.getBackupFileLocation();
        } else {
            uploadRootPath = PropertiesModel.CONFIG.getString("shieldsb.upload.fileRootPath", request.getServletContext().getRealPath("/"));
        }
        String day = DateUtil.getNowDateTime("yyyy-MM-dd_[HH_mm]");
        String testBakRoot = uploadRootPath + File.separator + "__sys_bak__" + File.separator + day;
        if (!FileUtils.exists(testBakRoot)) {
            FileUtils.createDirectory(testBakRoot);
        }

        DBbackupThread.EXECUTOR.execute(new DBbackupThread(dbSetInfo, backupSetModel, testBakRoot, Web.Util.getSessionUserId(request),
                Web.Util.getSessionUserName(request)));
    }

    public Result mysqlRecovery(DBSetInfo dbSetInfo, DbbackUpInfoModel backUpInfoModel) {
        if (!FileUtils.exists(backUpInfoModel.getBackupFilePath())) {
            return Web.Response.error("还原数据库文件不存在！");
        }

        DBRecoveryThread.EXECUTOR.execute(new DBRecoveryThread(dbSetInfo, backUpInfoModel, Web.Util.getSessionUserId(request)));
        return Web.Response.success("");
    }

    public Result isExitDownFile() {
        long id = getLong("id");
        if (id != 0) {
            DbbackUpInfoModel model = getOne(DbbackUpInfoModel.class, id);
            if (model != null && FileUtils.exists(model.getBackupFilePath())) {
                return Web.Response.success("");
            } else {
                return Web.Response.error("下载失败,文件已经不存在！");
            }
        }
        return Web.Response.error("未检测到文件，如已上传文件，请保存后重试。");
    }

    public void downloadAtt() throws ServletException, IOException {
        long id = getLong("id");
        DbbackUpInfoModel model = getOne(DbbackUpInfoModel.class, id);
        downloadLocalAtt(model.getBackupFileName(), model.getBackupFilePath(), response);
    }

    public void downloadLocalAtt(String downFileName, String remoteFilePath, HttpServletResponse response) {
        // 服务器绝对路径
        String path = remoteFilePath;
        File file = new File(path);
        String fileName = file.getName();
        response.setContentType("multipart/form-data");

        OutputStream fOut = null;
        InputStream inputStream;
        BufferedInputStream bufferedInputStream;
        try {
            fOut = response.getOutputStream();
            response.setHeader("content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
            inputStream = new FileInputStream(file);
            bufferedInputStream = new BufferedInputStream(inputStream, 1024 * 100);
            int read;
            byte[] bufferArea = new byte[1024 * 100];
            while ((read = bufferedInputStream.read(bufferArea, 0, 1024 * 100)) != -1) {
                fOut.write(bufferArea, 0, read);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fOut != null) {
                    fOut.flush();
                }
                if (fOut != null) {
                    fOut.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
